/*
 * @(#)MaintFormRecordAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.web;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.dcivision.form.bean.FormAttach;
import com.dcivision.form.bean.FormElement;
import com.dcivision.form.bean.FormElementType;
import com.dcivision.form.bean.FormGroup;
import com.dcivision.form.bean.FormPage;
import com.dcivision.form.bean.FormRecord;
import com.dcivision.form.bean.FormSection;
import com.dcivision.form.bean.FormSelectionField;
import com.dcivision.form.bean.FormSelectionFieldOption;
import com.dcivision.form.bean.FormSubmission;
import com.dcivision.form.bean.FormSubmissionHtml;
import com.dcivision.form.bean.MtmFormPageFormSection;
import com.dcivision.form.bean.MtmFormSectionFormElement;
import com.dcivision.form.core.FormBuilderHelper;
import com.dcivision.form.core.FormHttpOperation;
import com.dcivision.form.core.FormSubmissionManager;
import com.dcivision.form.dao.FormAttachDAObject;
import com.dcivision.form.dao.FormElementDAObject;
import com.dcivision.form.dao.FormGroupDAObject;
import com.dcivision.form.dao.FormPageDAObject;
import com.dcivision.form.dao.FormRecordDAObject;
import com.dcivision.form.dao.FormSectionDAObject;
import com.dcivision.form.dao.FormSelectionFieldDAObject;
import com.dcivision.form.dao.FormSelectionFieldOptionDAObject;
import com.dcivision.form.dao.FormSubmissionHtmlDAObject;
import com.dcivision.form.dao.MtmFormPageFormSectionDAObject;
import com.dcivision.form.dao.MtmFormSectionFormElementDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.Crypt;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;

/**
  MaintFormRecordAction.java

  This class is for maint user record.

    @author          Scott Tong
    @company         DCIVision Limited
    @creation date   10/12/2003
    @version         $Revision: 1.75.2.6 $
*/

public class MaintFormRecordAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.75.2.6 $";

  protected String listName = "";
  public MaintFormRecordAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.form.dao.FormRecordDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.FORM_SETUP);
  }

  /**
   * setPageTitle
   * set the extend page title and page path.
   * default page path/title will be created by navmode and functionCode
   * @throws ApplicationException 
   */
  public void setPageTitle(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping, ActionForward actionForward) throws ApplicationException{
    Integer formGroupID = Integer.valueOf(request.getSession().getAttribute("formGroupID").toString());
    FormGroupDAObject formGroupDAO = new FormGroupDAObject(this.getSessionContainer(request),this.getConnection(request));
    FormGroup formGroup = (FormGroup)formGroupDAO.getObjectByID(formGroupID);
    StringBuffer extendPath = new StringBuffer();
    extendPath.append("<a href=\"ListFormRecord.do?formGroupID="+formGroupID);
    extendPath.append("&opMode="+GlobalConstant.OP_MODE_LIST_RETAIN+"\">");
    extendPath.append(formGroup.getGroupName());
    extendPath.append("</a>");
    request.setAttribute(GlobalConstant.EXTEND_PAGE_PATH, extendPath.toString());
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    AbstractActionForm maintForm = (AbstractActionForm)form;
    MaintFormRecordForm formRecordForm = (MaintFormRecordForm)form;
    FormBuilderHelper formBuilderHelper = new FormBuilderHelper(this.getSessionContainer(request),this.getConnection(request));
    FormSubmissionHtmlDAObject formSubmissionHtmlDAO = new FormSubmissionHtmlDAObject(this.getSessionContainer(request),this.getConnection(request));

    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();
    String navMode = (maintForm!=null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();

    String directory = SystemParameterFactory.getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH);
    File dirFile = new File(directory);
    if (!dirFile.exists()){
      boolean isCreateFolder = false;
      isCreateFolder = dirFile.mkdirs();
      if(isCreateFolder){
      request.setAttribute("isCreateFolder", GlobalConstant.TRUE);
      }else{
      addError(request, "errors.form_no_physical_path_of_the_attachment");
      }
    }else{
        request.setAttribute("isCreateFolder", GlobalConstant.TRUE);
    }
    //handle the End Date is not Empty
    if(!Utility.isEmpty(formRecordForm.getEndDate()) ){
      Timestamp endDateTimestamp = Utility.parseDateStringToSystemDate(formRecordForm.getEndDate(), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
      Calendar endDateCal = Utility.timestampToCalendar(endDateTimestamp);
      endDateCal.set(Calendar.HOUR_OF_DAY, 23);
      endDateCal.set(Calendar.MINUTE, 59);
      endDateCal.set(Calendar.SECOND, 59);
      endDateCal.set(Calendar.MILLISECOND, 0);
      endDateTimestamp = Utility.calendarToTimestamp(endDateCal);
      formRecordForm.setEndDate(endDateTimestamp.toString());
    }
    String status = request.getParameter("status");
    request.setAttribute("formRecordID",formRecordForm.getID());

    if (GlobalConstant.OP_MODE_REFRESH.equals(opMode)) {
      // Set the function code for current action.
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
        return forward;
      }
      refreshFormData(mapping, maintForm, request, response);
      return mapping.findForward(GlobalConstant.NAV_MODE_REFRESH);
    } else if(GlobalConstant.OP_MODE_INSERT.equals(opMode) ||
              GlobalConstant.OP_MODE_INSERT_NEW.equals(opMode) ||
              GlobalConstant.OP_MODE_COPY.equals(opMode) ) {
      try {

        ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
        if (forward!=null) {
          return forward;
        }
        this.insertRecord(mapping,(AbstractActionForm)form,request,response);
        this.selectRecord(mapping,(AbstractActionForm)form,request,response);
      } catch (ApplicationException appEx) {
        formRecordForm.setID(null);
        this.handleApplicationException(request,appEx);
        if (GlobalConstant.OP_MODE_COPY.equals(opMode)){
          maintForm.setNavMode(GlobalConstant.NAV_MODE_CHANGE);
          request.setAttribute("formCopyID",request.getParameter("formRecordID"));
        }else{
          maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
        }
        return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
      }

      if (GlobalConstant.OP_MODE_COPY.equals(opMode) && formSubmissionHtmlDAO.getBooleanByRecordID(new Integer(maintForm.getID()))){
        maintForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
      }else{
        maintForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
        return mapping.findForward(GlobalConstant.NAV_MODE_CHANGE);
      }

    } else if(GlobalConstant.OP_MODE_UPDATE.equals(opMode) ||
              GlobalConstant.OP_MODE_UPDATE_NEW.equals(opMode) ) {
      try{
        ActionForward forward = this.retrieveFunctionCode(request, response,
            mapping);
        if (forward != null) {
          return forward;
        }
        this.updateRecord(mapping, (AbstractActionForm) form, request, response);
      }catch (ApplicationException appEx) {
        this.handleApplicationException(request,appEx);
        formRecordForm.setStatus(GlobalConstant.RECORD_PENDING);
        maintForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
        return mapping.findForward(GlobalConstant.NAV_MODE_EDIT);
      }

      this.selectRecord(mapping,(AbstractActionForm)form,request,response);
      return mapping.findForward(GlobalConstant.NAV_MODE_CHANGE);
    } else {
      return super.execute(mapping, form, request, response);
    }
  }

  public void refreshFormData(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    List resultList = new ArrayList();

    try {
      SessionContainer sessionCon = this.getSessionContainer(request);
      MaintFormRecordForm formRecordForm = (MaintFormRecordForm)form;
      int listSize = 0;
      int intNewField =0;
      try {
        listSize = TextUtility.parseInteger(request.getParameter("listSize"));
        intNewField = TextUtility.parseInteger(request.getParameter("newField"));
      } catch (Exception e) {
        throw new ApplicationException (ErrorConstant.COMMON_FATAL_ERROR, e);
      }

      int sum=0;
      sum=listSize+intNewField;

      //Get Header Form data
      FormRecord formRecord = (FormRecord)formRecordForm.getFormData();

      //Set Header Form data
      formRecordForm.setFormData(formRecord);
      formRecordForm.setPageTitle(formRecordForm.getPageTitle());

      for (int i = 0; i < listSize; i++){
        FormSection tmpFormSection = new FormSection();
        if (!("".equals(request.getParameter("formSectionID_"+i))) && !("null".equals(request.getParameter("formSectionID_"+i)))) {
          tmpFormSection.setID(new Integer(request.getParameter("formSectionID_"+i)));
        }
        //if (userDefinedIndexForm.getID()!=null && (!"null".equals(userDefinedIndexForm.getID())))
        //    tmpSysUserDefinedIndexDetail.setUserDefinedID(userDefinedIndexForm.getID());
        if (!("".equals(request.getParameter("formSectionTitle_"+i))) && (!"null".equals(formRecord.getID()))) {
          tmpFormSection.setTitle(new String (request.getParameter("formSectionTitle_"+i)));
        }
        if (!("".equals(request.getParameter("formSectionDesc_"+i))) && (!"null".equals(formRecord.getID()))) {
          tmpFormSection.setDescription(new String (request.getParameter("formSectionDesc_"+i)));
        }

        String strDeleteCheckValue = request.getParameter("delete_"+i);
        if (strDeleteCheckValue == null){
          resultList.add(tmpFormSection);
        }
      }
      formRecordForm.setFormSectionListData(resultList);
      formRecordForm.setFormSectionList(formRecordForm.getFormSectionList());

      request.setAttribute("listSize", new Integer(listSize));
      request.setAttribute("newFieldsSize", new Integer(sum));
      request.setAttribute("newField", new Integer(intNewField));
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e){
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
    }
  }

  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    List resultList = new ArrayList();
    AbstractActionForm maintForm = form;
    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();

    try {
      MaintFormRecordForm formRecordForm = (MaintFormRecordForm)form;
      // Create From record.
      FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
      FormRecord formRecord = (FormRecord)formRecordForm.getFormData();
      //formRecord.setCurrent_no(formRecord.getStart_no());
      String formDocID = null;
      formRecord = (FormRecord)formRecordDAO.insertObject(formRecord);

      // Create Fields for the Form page
      //int listSize = new Integer(request.getParameter("listSize")).intValue();
      String fontStyle="";
     if (request.getParameter("fontStyleBold")!=null) {
      fontStyle+="B";
    }
     if (request.getParameter("fontStyleUnderline")!=null) {
      fontStyle+="U";
    }
     if (request.getParameter("fontStyleItalic")!=null) {
      fontStyle+="I";
    }
      String pageTitle = (!Utility.isEmpty(request.getParameter("pageTitle"))) ? request.getParameter("pageTitle") : "1";
      FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));
      FormPage tmpFormPage = new FormPage();
      tmpFormPage.setFormRecordID(formRecord.getID());
      tmpFormPage.setTitleFontColor(formRecordForm.getTitleFontColor());
      tmpFormPage.setTitleFontSize(TextUtility.parseIntegerObj(formRecordForm.getTitleFontSize()));

      tmpFormPage.setTitleFontStyle(fontStyle);
      tmpFormPage.setTitleFontType(formRecordForm.getTitleFontType());
      tmpFormPage.settitlePosition(formRecordForm.getTitlePosition());
      tmpFormPage.setTitle(pageTitle);
      tmpFormPage.setPageNo(new Integer(0));

      FormPage formPage = null;
      formPage = (FormPage)formPageDAO.insertObject(tmpFormPage);

      formRecordForm.setFormData(formRecord);
      formRecordForm.setPageTitle(formPage.getTitle());
      formRecordForm.setPageID(formPage.getID());

      //    if navMode is copy then copy all elements to DB.
      if(GlobalConstant.OP_MODE_COPY.equals(opMode)){
        copyElement(mapping, form, request, response);
        getConnection(request).commit();
      }

      this.getConnection(request).commit();
      request.setAttribute("formRecordID",formRecordForm.getID());
      request.setAttribute("formPageID",tmpFormPage.getID());
      request.setAttribute("formRecordUpdateCount",formRecordForm.getUpdateCount());
      request.setAttribute("listSize", null);
      request.setAttribute("newFieldsSize",null);
      request.setAttribute("newField", null);
      refreshList(request, GlobalConstant.OP_MODE_INSERT, formRecord);

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {}
  }

  public void refreshList(HttpServletRequest request, String opMode, com.dcivision.framework.bean.AbstractBaseObject obj) {
    java.util.ArrayList list = (java.util.ArrayList)request.getAttribute(this.listName);
    if (list != null) {
      if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
        list.add(obj);
      } else if (GlobalConstant.OP_MODE_UPDATE.equals(opMode)) {
        for (int i = 0; i < list.size(); i++) {
          if (obj.equals(list.get(i))) {
            list.remove(i);
            list.add(i, obj);
          }
        }
      } else if (GlobalConstant.OP_MODE_DELETE.equals(opMode)) {
        for (int i = 0; i < list.size(); i++) {
          if (obj.equals(list.get(i))) {
            list.remove(i);
          }
        }
      }
    }
  }

  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    try {
      int elementTotal = 0;
      Hashtable elementHashtable = new Hashtable();
      MaintFormRecordForm formRecordForm = (MaintFormRecordForm)form;
      //get form record
      Integer FormRecordID = TextUtility.parseIntegerObj(formRecordForm.getID());
      FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
      FormRecord formRecord = (FormRecord)formRecordDAO.getObjectByID(FormRecordID);

      formRecordForm.setFormData(formRecord);
      //get form page
      FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));
      List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(FormRecordID,new Integer(0));
      for (int j = 0; j < formPageList.size(); j++){
        elementTotal = 0;
        FormPage formPage = (FormPage)formPageList.get(j);
        if (j==0) {
          formRecordForm.setPageTitle(formPage.getTitle());
          formRecordForm.setTitleFontColor(formPage.getTitleFontColor());
          formRecordForm.setTitleFontSize((""+formPage.getTitleFontSize()).trim());
          formRecordForm.setTitleFontStyle(formPage.getTitleFontStyle());
          formRecordForm.setTitleFontType(formPage.getTitleFontType());
          formRecordForm.setTitlePosition(formPage.gettitlePosition());
        }
        request.setAttribute("formPageID",formPage.getID());
        request.setAttribute("formRecordID",formRecordForm.getID());
        request.setAttribute("formGroupID",formPage.getGroupID());
        request.setAttribute("formRecordUpdateCount",formRecordForm.getUpdateCount());
        request.setAttribute("formRecordStatus",formRecord.getStatus());

        //get form section
        FormSectionDAObject FormSectionDAO = new FormSectionDAObject(this.getSessionContainer(request), this.getConnection(request));
        List formSectionList = FormSectionDAO.getListByFormPageID(formPage.getID());
        for (int i = 0; i < formSectionList.size(); i++) {
          FormSection formSection = (FormSection)formSectionList.get(i);
          FormElementDAObject FormElementDAO = new FormElementDAObject(this.getSessionContainer(request), this.getConnection(request));
          List formElementList = FormElementDAO.getListByFormSectionID(
              formSection.getID());
          if (!Utility.isEmpty(formElementList)) {
            elementTotal += formElementList.size();
          }
          elementHashtable.put(formSection.getID(),formElementList);
        }
       // elementTotal = 0;
        request.setAttribute("formSectionList"+j,formSectionList);
        request.setAttribute("formElementHashtable"+j,elementHashtable);
        request.setAttribute("listSize_"+formPage.getID().toString(),new Integer(formSectionList.size() + elementTotal));
      }

      //get display element id list.
      FormSubmissionManager formSubmissionManager = new FormSubmissionManager(this.getSessionContainer(request),this.getConnection(request));
      List formElementList = formSubmissionManager.getRelatedItemListByFormRecordID(formRecordForm.getID());
      request.setAttribute("formElementList", formElementList);

      request.setAttribute("formPageList",formPageList);

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
    } finally {}
  }

  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    List resultList = new ArrayList();
    try {
      MaintFormRecordForm formRecordForm = (MaintFormRecordForm)form;
      // Update From record.
      FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
      FormRecord formRecord = (FormRecord)formRecordForm.getFormData();
//      if(formRecord.getCurrent_no().intValue()<formRecord.getStart_no().intValue()){
//      	formRecord.setCurrent_no(formRecord.getStart_no());
//      }
      formRecord = (FormRecord)formRecordDAO.updateObject(formRecord);
      String fontStyle="";
     if (request.getParameter("fontStyleBold")!=null) {
      fontStyle+="B";
    }
     if (request.getParameter("fontStyleUnderline")!=null) {
      fontStyle+="U";
    }
     if (request.getParameter("fontStyleItalic")!=null) {
      fontStyle+="I";
    }

     //Update Form page.
    String pageTitle = request.getParameter("pageTitle");
   FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));
   FormPage formPage = (FormPage)formPageDAO.getFirstPageByFormRecordID(formRecord.getID());
   formPage.setFormRecordID(formRecord.getID());
   //formPage.setID(formRecordForm.getPageID());
   formPage.setTitleFontColor(formRecordForm.getTitleFontColor());
   formPage.setTitleFontSize(TextUtility.parseIntegerObj(formRecordForm.getTitleFontSize()));
   formPage.setTitleFontStyle(fontStyle);
   formPage.setTitleFontType(formRecordForm.getTitleFontType());
   formPage.settitlePosition(formRecordForm.getTitlePosition());

   formPage.setTitle(pageTitle);

   formPage = (FormPage)formPageDAO.updateObject(formPage);
   formRecordForm.setPageTitle(formPage.getTitle());
   request.setAttribute("formPageID",formPage.getID());
     //set Form data
     formRecordForm.setFormData(formRecord);
     request.setAttribute("formRecordID",formRecordForm.getID());
     request.setAttribute("formRecordUpdateCount",formRecordForm.getUpdateCount());
     this.getConnection(request).commit();
     request.setAttribute("listSize", null);
     request.setAttribute("newFieldsSize", null);
     request.setAttribute("newField", null);
     refreshList(request, GlobalConstant.OP_MODE_INSERT, formRecord);

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {}
  }

  public void copyElement(ActionMapping mapping,
                           AbstractActionForm form,
                           HttpServletRequest request,
                           HttpServletResponse response) throws ApplicationException {

    MaintFormRecordForm formRecordForm = (MaintFormRecordForm)form;
    String copyID = request.getParameter("formRecordID");
    String formRecordID = formRecordForm.getID();
    Integer pageID = formRecordForm.getPageID();
    try {
      FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request),this.getConnection(request));
      FormSectionDAObject formSectionDAO = new FormSectionDAObject(this.
          getSessionContainer(request), this.getConnection(request));
      FormElementDAObject formElementDAO = new FormElementDAObject(this.
          getSessionContainer(request), this.getConnection(request));
      FormAttachDAObject formAttachDAO = new FormAttachDAObject(this.
          getSessionContainer(request), this.getConnection(request));
      MtmFormSectionFormElementDAObject mtmFormSectionFormElementDAO =
          new MtmFormSectionFormElementDAObject(this.getSessionContainer(request),
                                                this.getConnection(request));
      MtmFormPageFormSectionDAObject mtmFormPageFormSectionDAO = new
          MtmFormPageFormSectionDAObject(this.getSessionContainer(request),
                                         this.getConnection(request));
      FormSelectionFieldDAObject FormSelectionFieldDAObject = new
      FormSelectionFieldDAObject(this.getSessionContainer(request),
                                 this.getConnection(request));
      FormSelectionFieldOptionDAObject FormSelectionFieldOptionDAObject = new
      FormSelectionFieldOptionDAObject(this.getSessionContainer(request),
                                       this.getConnection(request));

      int pageSeqNo = 0;
      int sectionSeqNo = 0;
      int elementSeqNo = 0;

      List tmpPageList = formPageDAO.getDetailListByFormRecordIDStepID(new Integer(copyID),new Integer(0));
      for (int i=0; i<tmpPageList.size(); i++){
        FormPage tmpFormPage =(FormPage) tmpPageList.get(i);
        //Insert Form_Page table.
        if (i>0){
          pageSeqNo++;
          tmpFormPage.setPageNo(new Integer(pageSeqNo));
          tmpFormPage.setFormRecordID(new Integer(formRecordForm.getID()));
          FormPage formPage = (FormPage)formPageDAO.insertObject(tmpFormPage);
          pageID = formPage.getID();
        }

        //Insert Form_Section,Mtm_Form_Page_Form_Section table.
        List tmpSectionList = tmpFormPage.getFormSectionList();
        for (int j=0; j<tmpSectionList.size(); j++){
          sectionSeqNo++;
          FormSection tmpSection = (FormSection)tmpSectionList.get(j);
          MtmFormPageFormSection tmpMtmFormPageFormSection = new
          MtmFormPageFormSection();
          FormSection formSection = (FormSection)formSectionDAO.insertObject(tmpSection);
          tmpMtmFormPageFormSection.setPageID(pageID);
          tmpMtmFormPageFormSection.setSectionID(formSection.getID());
          tmpMtmFormPageFormSection.setSectionSeq(new Integer(sectionSeqNo));
          mtmFormPageFormSectionDAO.insertObject(tmpMtmFormPageFormSection);

          //Insert Form_Element,Mtm_Form_Section_Form_Element table.
          List tmpElementList = tmpSection.getFormElementList();
          for (int k=0; k<tmpElementList.size(); k++){
            elementSeqNo++;
            FormElement tmpElement = (FormElement)tmpElementList.get(k);
            MtmFormSectionFormElement tmpMtmFormSectionFormElement = new MtmFormSectionFormElement();
            FormAttach tmpFormAttach = new FormAttach();
            if (tmpElement.getElementType().equals(FormElementType.ELEMENT_IMAGE)){
              tmpFormAttach = (FormAttach) formAttachDAO.getObjectByID(tmpElement.getID())!=null ? (FormAttach) formAttachDAO.getObjectByID(tmpElement.getID()) : tmpFormAttach;
              tmpElement.setFileName(tmpFormAttach.getFileName());
            }
            FormElement formElement = (FormElement)formElementDAO.insertObject(tmpElement);

            tmpMtmFormSectionFormElement.setSectionID(formSection.getID());
            tmpMtmFormSectionFormElement.setElementID(formElement.getID());
            tmpMtmFormSectionFormElement.setElementSeq(new Integer(elementSeqNo));
            mtmFormSectionFormElementDAO.insertObject(tmpMtmFormSectionFormElement);
            //Insert Form_Attach table.
            if (tmpElement.getElementType().equals(FormElementType.ELEMENT_IMAGE)){
              FormAttach formAttach = (FormAttach) formAttachDAO.getObjectByID(formElement.getID());
              String path = SystemParameterFactory.getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH);
              String fileName ="", copyFileName ="";
              if (!Utility.isEmpty(tmpFormAttach.getFileName()) && !"null".equals(tmpFormAttach.getFileName())){
                fileName = path + "/" + formAttach.getID().toString() + tmpFormAttach.getFileName().substring(tmpFormAttach.getFileName().indexOf("."),tmpFormAttach.getFileName().length());
                copyFileName = path + "/" + tmpFormAttach.getID().toString() + tmpFormAttach.getFileName().substring(tmpFormAttach.getFileName().indexOf("."),tmpFormAttach.getFileName().length());
                FormBuilderHelper formBuilderHelper = new FormBuilderHelper();
                formBuilderHelper.saveAsFile(copyFileName,fileName);
              }
            }
            //Insert Form_Selection_Field, Form_Selection_Field_Option table.
            if (FormElementType.isSelection(formElement.getElementType())) {
              FormSelectionField tmpFormSelectionField = tmpElement.getFormSelectionField();
              tmpFormSelectionField.setElementID(formElement.getID());
              FormSelectionField formSelectionField = (FormSelectionField)FormSelectionFieldDAObject.insertObject(tmpFormSelectionField);
              List tmpSelectionFieldOptionList = tmpFormSelectionField.getFormSelectionFieldOptionList();
              for (int n = 0; n < tmpSelectionFieldOptionList.size(); n++) {
                FormSelectionFieldOption tmpFormSelectionFieldOption = (FormSelectionFieldOption)tmpSelectionFieldOptionList.get(n);
                tmpFormSelectionFieldOption.setSelectionFieldID(formSelectionField.getID());
                FormSelectionFieldOptionDAObject.insertObject(
                    tmpFormSelectionFieldOption);
              }
            }
          }
        }

      }
      //this.getConnection(request).commit();
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }
  }

  public void insertStructureToDB (File file,HttpServletRequest request,
             HttpServletResponse response)
    throws SAXException,IOException,ApplicationException {
    //get DAO
    FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.
    getSessionContainer(request), this.getConnection(request));
    FormPageDAObject formPageDAO = new FormPageDAObject(this.
    getSessionContainer(request), this.getConnection(request));
    FormSectionDAObject formSectionDAO = new FormSectionDAObject(this.
    getSessionContainer(request), this.getConnection(request));
    FormElementDAObject formElementDAO = new FormElementDAObject(this.
    getSessionContainer(request), this.getConnection(request));
    MtmFormSectionFormElementDAObject mtmFormSectionFormElementDAO =
    new MtmFormSectionFormElementDAObject(
    this.getSessionContainer(request), this.getConnection(request));
    MtmFormPageFormSectionDAObject mtmFormPageFormSectionDAO = new
    MtmFormPageFormSectionDAObject(this.getSessionContainer(request),
                this.getConnection(request));

    //get xml
    DocumentBuilder builder = null;
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      builder = factory.newDocumentBuilder();
    } catch (Exception ex) {
      log.error(ex, ex);
    }
    String recordID = null;
    String pageID = null;
    String sectionID = null;
    String elementID = null;
    String navMode = null;
    try{
        Document document = builder.parse(file);
        NodeList nodesFormList = document.getDocumentElement().getChildNodes();
        for (int n = 0; n < nodesFormList.getLength(); n++) {
          Node nodeRecord = nodesFormList.item(n);

        if (nodeRecord.getNodeType() == Node.ELEMENT_NODE &&
            "FormRecord".equals( ((Element)nodeRecord).getTagName()) ){
          Element recordEle = (Element)nodeRecord;
          recordID = recordEle.getAttribute("ID");
          navMode = recordEle.getAttribute("navMode");
        }

        // Page
        NodeList nodesPageList = nodeRecord.getChildNodes();
        for (int i = 0; i < nodesPageList.getLength(); i++) {
          Node nodePage = nodesPageList.item(i);
        if (nodePage.getNodeType() == Node.ELEMENT_NODE && "Page".equals( ((Element)nodePage).getTagName())   ) {
        Element pageEle = (Element)nodePage;
        pageID = pageEle.getAttribute("ID");

        }

        // Handel Section
        int sectionSeqNo = 0;
        NodeList nodesSectionList = nodePage.getChildNodes();
        for (int j = 0; j < nodesSectionList.getLength(); j++) {
          Node nodeSection = nodesSectionList.item(j);

          FormSection tmpFormSection = new FormSection();
          if (nodeSection.getNodeType() == Node.ELEMENT_NODE && "Section".equals(
            ( (Element) nodeSection).getTagName())) {
            sectionSeqNo++;
            Element sectionEle = (Element) nodeSection;
            String subSection = sectionEle.getAttribute("isSubSection");
            //String sectionTitle = sectionEle.getAttribute("name");

            //Insert Form_Section Table
            tmpFormSection.setSubSection(subSection);
            tmpFormSection.setTitle("section"+sectionSeqNo);

            tmpFormSection = (FormSection)formSectionDAO.insertObject(tmpFormSection);

            // Insert Mtm_Form_Page_Form_Section Table
            MtmFormPageFormSection tmpMtmFormPageFormSection = new MtmFormPageFormSection();
            tmpMtmFormPageFormSection.setPageID(new Integer(pageID));
            tmpMtmFormPageFormSection.setSectionID(tmpFormSection.getID());
            tmpMtmFormPageFormSection.setSectionSeq(new Integer(sectionSeqNo));
            mtmFormPageFormSectionDAO.insertObject(tmpMtmFormPageFormSection);

          }
            // Handel Element
          int elementSeqNo = 0;
          NodeList nodesElementList = nodeSection.getChildNodes();
          for (int k = 0; k < nodesElementList.getLength(); k++) {
            elementSeqNo++;
            Node nodeElement = nodesElementList.item(k);
            if (nodeElement.getNodeType() == Node.ELEMENT_NODE && "Element".equals(
                ( (Element) nodeElement).getTagName())) {
              Element elementEle = (Element) nodeElement;
              String elementName = elementEle.getAttribute("name");
                String elementType = elementEle.getAttribute("type");
              String elementValue = elementEle.getAttribute("value");

              //Insert Form_Element
              FormElement tmpFormElement = new FormElement();
              tmpFormElement.setFieldName(elementName);
              tmpFormElement.setElementType(elementType);
              tmpFormElement.setRequiredFlag("N");

              if (elementName.startsWith("Text") && !Utility.isEmpty(elementValue) && !"null".equals(elementValue) ){
                tmpFormElement.setIsLabel("Y");
              }else{
                tmpFormElement.setIsLabel("N");
              }
              tmpFormElement = (FormElement)formElementDAO.insertObject(tmpFormElement);

              //Insert Mtm_Form_Section_Form_Element Table
              MtmFormSectionFormElement tmpFormSectionFormElement = new
              MtmFormSectionFormElement();
              tmpFormSectionFormElement.setElementID(tmpFormElement.getID());
              tmpFormSectionFormElement.setSectionID(tmpFormSection.getID());
              tmpFormSectionFormElement.setElementSeq(new Integer(elementSeqNo));
              mtmFormSectionFormElementDAO.insertObject(tmpFormSectionFormElement);

            }
          }
        }
       }
     }
     this.commit(request);
    }catch (ApplicationException appEx) {
    throw appEx;
    } catch (Exception e) {
    log.error(e, e);
    throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
    }

}

  public void updateStructureToDB(File file,HttpServletRequest request,HttpServletResponse response)throws ApplicationException {
    DocumentBuilder builder = null;
    try {
      DocumentBuilderFactory factory =
          DocumentBuilderFactory.newInstance();
      builder = factory.newDocumentBuilder();
    } catch (Exception ex) {
      log.error(ex, ex);
    }
    String recordID = null;
    String formSubmissionID = null;
    String pageID = null;
    String sectionID = null;
    String elementID = null;
    String submissionID = null;
    String status = null;
    // Get DAO
    FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
    FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));
    FormSectionDAObject formSectionDAO = new FormSectionDAObject(this.getSessionContainer(request), this.getConnection(request));
    FormElementDAObject formElementDAO = new FormElementDAObject(this.getSessionContainer(request), this.getConnection(request));
    MtmFormSectionFormElementDAObject mtmFormSectionFormElementDAO =new MtmFormSectionFormElementDAObject(
            this.getSessionContainer(request), this.getConnection(request));
    MtmFormPageFormSectionDAObject mtmFormPageFormSectionDAO = new MtmFormPageFormSectionDAObject(this.getSessionContainer(request),
            this.getConnection(request));

    try {
      Document document = builder.parse(file);
      NodeList nodesFormList = document.getDocumentElement().getChildNodes();

      for (int n = 0; n < nodesFormList.getLength(); n++) {
            Node nodeRecord = nodesFormList.item(n);
        FormSubmission formSubmission = new FormSubmission();
        if (nodeRecord.getNodeType() == Node.ELEMENT_NODE &&
                "FormRecord".equals( ((Element)nodeRecord).getTagName()) ){
            Element recordEle = (Element)nodeRecord;
          recordID = recordEle.getAttribute("ID");
          formSubmissionID = recordEle.getAttribute("FormSubmissionID");
          if ("true".equals(recordEle.getAttribute("isEdit"))){
              status = "S";
           }
        } else {
          continue;
        }

        // get Page info
        NodeList nodesPageList = nodeRecord.getChildNodes();
        for (int i = 0; i < nodesPageList.getLength(); i++) {
          Node nodePage = nodesPageList.item(i);
          if (nodePage.getNodeType() == Node.ELEMENT_NODE && "Page".equals( ((Element)nodePage).getTagName())   ) {
            Element pageEle = (Element)nodePage;
            FormPage formPage = (FormPage)formPageDAO.getFirstPageByFormRecordID(new Integer(recordID));   //pdf only a page
            pageID = formPage.getID().toString();

            //delete old date for the page
            List formSectionList = formSectionDAO.getDetailListByFormPageID(new Integer(pageID));
            List mtmFormPageFormSectionList = mtmFormPageFormSectionDAO.getListByPageID(new Integer(pageID));
            String[] formSectionListArr = new String[formSectionList.size()];
            String[] mtmFormPageFormSectionArr = new String[mtmFormPageFormSectionList.size()];
            //delete date form MTM_FORM_PAGE_FORM_SECTION,FORM_SECTION,MTM_FORM_SECTION_FORM_ELEMENT,FORM_ELEMENT table
            if(mtmFormPageFormSectionList.size()>0){
              for (int jj=0; jj<mtmFormPageFormSectionList.size(); jj++){
                MtmFormPageFormSection mtmFormPageFormSection =(MtmFormPageFormSection)mtmFormPageFormSectionList.get(jj);
                mtmFormPageFormSectionArr[jj] = mtmFormPageFormSection.getID().toString();
                formSectionListArr[jj] = mtmFormPageFormSection.getSectionID().toString();

                List mtmFormSectionFormElementList = mtmFormSectionFormElementDAO.getListBySectionID(mtmFormPageFormSection.getSectionID());
                String[] mtmFormSectionFormElementListArr = new String[mtmFormSectionFormElementList.size()];
                String[] formElementListArr = new String[mtmFormSectionFormElementList.size()];
                if(mtmFormSectionFormElementList.size()>0){
                  for (int kk=0; kk<mtmFormSectionFormElementList.size(); kk++){
                    MtmFormSectionFormElement mtmFormSectionFormElement =(MtmFormSectionFormElement)mtmFormSectionFormElementList.get(kk);
                    mtmFormSectionFormElementListArr[kk] = mtmFormSectionFormElement.getID().toString();
                    formElementListArr[kk] = mtmFormSectionFormElement.getElementID().toString();
                    }
                  if(mtmFormPageFormSectionArr.length>0){
                    mtmFormSectionFormElementDAO.deleteList(mtmFormSectionFormElementListArr);
                    formElementDAO.deleteList(formElementListArr);
                  }
                }

                }
              if(mtmFormPageFormSectionArr.length>0){
                mtmFormPageFormSectionDAO.deleteList(mtmFormPageFormSectionArr);
                formSectionDAO.deleteList(formSectionListArr);
              }
            }

           } else {
            continue;
          }

           // get section info
           NodeList nodesSectionList = nodePage.getChildNodes();
           // get all section in this page
           List mtmFormPageFormSectionList = mtmFormPageFormSectionDAO.getListByPageID(new Integer(pageID));

           int sectionSeqNo = 0;
           for (int j = 0; j < nodesSectionList.getLength(); j++) {
             Node nodeSection = nodesSectionList.item(j);
             FormSection tmpFormSection = new FormSection();
             if (nodeSection.getNodeType() == Node.ELEMENT_NODE && "Section".equals(
                ( (Element) nodeSection).getTagName())) {
               Element sectionEle = (Element) nodeSection;
               sectionSeqNo ++;
               //Delete all old data

//             Insert Form_Section Table
               String subSection = sectionEle.getAttribute("isSubSection");
               //String sectionTitle = sectionEle.getAttribute("name");
               tmpFormSection.setSubSection(subSection);
               tmpFormSection.setTitle("section"+sectionSeqNo);

               tmpFormSection = (FormSection)formSectionDAO.insertObject(tmpFormSection);

               // Insert Mtm_Form_Page_Form_Section Table
               MtmFormPageFormSection tmpMtmFormPageFormSection = new MtmFormPageFormSection();
               tmpMtmFormPageFormSection.setPageID(new Integer(pageID));
               tmpMtmFormPageFormSection.setSectionID(tmpFormSection.getID());
               tmpMtmFormPageFormSection.setSectionSeq(new Integer(sectionSeqNo));
               mtmFormPageFormSectionDAO.insertObject(tmpMtmFormPageFormSection);
//

             } else {
               continue;
             }

             //get Element list
             NodeList nodesElementList = nodeSection.getChildNodes();
             //get all element in this section
             int elementSeqNo = 0;
             for (int k = 0; k < nodesElementList.getLength(); k++) {
               //for (int k = 0; k < mtmFormSectionFormElementList.size(); k++) {
               elementSeqNo++;
               Node nodeElement = nodesElementList.item(k);
               if (nodeElement.getNodeType() == Node.ELEMENT_NODE && "Element".equals(
                            ( (Element) nodeElement).getTagName())) {
                 Element elementEle = (Element) nodeElement;
                 String elementName = elementEle.getAttribute("name");
                 String elementType = elementEle.getAttribute("type");
                 String elementValue = elementEle.getAttribute("value");
                 //Insert Form_Element
                 FormElement tmpFormElement = new FormElement();
                 tmpFormElement.setFieldName(elementName);
                 tmpFormElement.setElementType(elementType);
                 tmpFormElement.setRequiredFlag("N");
                 if (elementName.startsWith("Text") && !Utility.isEmpty(elementValue) && !"null".equals(elementValue) ){
                   tmpFormElement.setIsLabel("Y");
                 }else{
                   tmpFormElement.setIsLabel("N");
                 }
                 tmpFormElement = (FormElement)formElementDAO.insertObject(tmpFormElement);

                 //Insert Mtm_Form_Section_Form_Element Table
                 MtmFormSectionFormElement tmpFormSectionFormElement = new
                            MtmFormSectionFormElement();
                 tmpFormSectionFormElement.setElementID(tmpFormElement.getID());
                 tmpFormSectionFormElement.setSectionID(tmpFormSection.getID());
                 tmpFormSectionFormElement.setElementSeq(new Integer(elementSeqNo));
                 mtmFormSectionFormElementDAO.insertObject(tmpFormSectionFormElement);

                }
              }
            }
          }
        }
        this.commit(request);
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
    } finally {}

  }

  public void copyHtmlFileToDB(AbstractActionForm form, HttpServletRequest request)throws ApplicationException {
    MaintFormRecordForm formRecordForm = (MaintFormRecordForm)form;
    SessionContainer sessionCon = this.getSessionContainer(request);
    Connection dbConn = this.getConnection(request);
    String loginName = sessionCon.getUserRecord().getLoginName();
    String loginPsw = Crypt.decrypt(
            sessionCon.getUserRecord().getLoginPwd(),
                SystemParameterFactory.getSystemParameter(SystemParameterConstant.CRYPTO_SALT));
    String httpURL = SystemParameterFactory.getSystemParameter(SystemParameterConstant.APPLICATION_BASE_URL) ;
    String sContent ="";
    String formRecordID = formRecordForm.getID();
    FormHttpOperation formHttpOperation = new FormHttpOperation();
    FormSubmissionHtmlDAObject formSubmissionHtmlDAO = new FormSubmissionHtmlDAObject(sessionCon,dbConn);
    FormPageDAObject formPageDAO = new FormPageDAObject(sessionCon,dbConn);
    FormSubmissionHtml formSubmissionHtml = new FormSubmissionHtml();
    try{
      boolean bl = formHttpOperation.login(httpURL+"/Login.do",loginName,loginPsw);
      String url = httpURL+"/form/MaintFormPage.do?navMode=E&formRecordID="+formRecordID+"&preview=E&SHOW_HEADER_FOOTER=N";
      formHttpOperation.reset() ;
      formHttpOperation.setSubmissionURL(url);
      sContent = formHttpOperation.transmit("");
      List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(new Integer(formRecordID),new Integer(0));
      for (int pp =0; pp<formPageList.size(); pp++){
        FormPage formPage = (FormPage)formPageList.get(pp);
        List formSectionList = formPage.getFormSectionList();
        for (int i = 0;i < formSectionList.size();i++){
          formSubmissionHtml.setFormRecordID(new Integer(formRecordID));
          formSubmissionHtml.setFormPageID(formPage.getID());
          formSubmissionHtml.setVersion("1");
          formSubmissionHtml.setStatus("A");
          FormSection formSection = (FormSection)formSectionList.get(i);
          formSubmissionHtml.setFormSectionID(formSection.getID());
          StringBuffer sb = new StringBuffer();
          Object object = sContent.substring(sContent.indexOf("<!--BEGIN SectionID"+formSection.getID()+"-->"),sContent.indexOf("<!--END SectionID"+formSection.getID()+"-->"));
          try{
            formSubmissionHtml.setPageHtml(object);
          }catch (Exception e){
            log.info(ErrorConstant.FORM_IMPORT_HTML_NOT_FOUND_SECTION);
            throw new ApplicationException(ErrorConstant.FORM_IMPORT_HTML_NOT_FOUND_SECTION);
          }
          formSubmissionHtmlDAO.insertObject(formSubmissionHtml);
        }
      }
    }catch(Exception ex){
      throw new ApplicationException(ex);
    }
  }


}